package my.senix.sc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lhs on 2018/11/8.
 */
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisContrroller {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("put")
    public String put(@RequestParam String aa) {
        redisTemplate.opsForValue().set("aa", aa);
        return "ok";
    }

    @GetMapping("get")
    public Map<String, String> get(@RequestParam String keys) {
        Map<String, String> map = new HashMap<>();

        String[] split = keys.split(",");

        for (String s : split) {
            map.put(s, redisTemplate.opsForValue().get(s));
        }

        Object nativeConnection = redisTemplate.getConnectionFactory().getConnection().getNativeConnection();
        if(nativeConnection instanceof Jedis){
            log.info("这是一个lettuce");
        }

        return map;
    }

    @GetMapping("pipeline")
    public List<Object> pipeline(){
        return redisTemplate.executePipelined((RedisCallback<Object>) connections -> {
            StringRedisConnection connection = (StringRedisConnection) connections;

            connection.set("name","lhs");
            connection.lPush("mylist","1","2","3","4");

            Map<String,String> map=new HashMap<>();
            map.put("keyq","value2");
            map.put("key2","value4");
            map.put("key3","value5");
            connection.hMSet("myHash",map);

            connection.get("aa");

            return null;
        });
    }
}
